package com.itheima04;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class ReflectDemo2 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        // 获取 class 对象
        Class<?> c = Class.forName("com.itheima02.Student");

        // Student s = new Student();
        Constructor<?> constructor = c.getConstructor();
        Object o = constructor.newInstance();
        System.out.println(o);

        // s.name = "林青霞";
//        Field nameField = c.getField("name");
        Field nameField = c.getDeclaredField("name");
        nameField.setAccessible(true); // 暴力反射
        nameField.set(o, "林青霞");

        // s.age = 30;
        Field ageField = c.getDeclaredField("age");
        ageField.setAccessible(true);
        ageField.set(o, 30);

        // s.address = "西安";
        Field addressField = c.getDeclaredField("address");
        addressField.setAccessible(true);
        addressField.set(o, "西安");
        System.out.println(o);

    }
}
